using JT808Protocol.Common;
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace JT808Protocol.Models.BodyParserStrategy.Authenticate
{
    /// <summary>
    /// 0x8100终端注册应答消息体
    /// </summary>
    public class DpDevRegisterResponse_0x8100 : IJT808Body
    {
        /// <summary>
        /// 应答流水号
        /// </summary>
        [JsonPropertyName("应答流水号")] public ushort SerialNum { get; set; }

        /// <summary>
        /// 结果
        /// </summary>
        [JsonPropertyName("结果")] public EnumDevRegisterType Result { get; set; }

        /// <summary>
        /// 鉴权码
        /// </summary>
        [JsonPropertyName("鉴权码")] public string AuthenticationCode { get; set; }

        public override IJT808Body ReadBody(ReadOnlySpan<byte> data, ref int index)
        {
            SerialNum = ParseHelper.Uint16(ref data, index);
            index += 2;
            Result = (EnumDevRegisterType)data[index];
            index++;
            AuthenticationCode = ParseHelper.Gb2312String(ref data, index, data.Length - index - 2);
            return this;
        }

        public override List<byte> WriteToBytes()
        {
            List<byte> bytes = new List<byte>();
            
            //应答流水号
            bytes.AddRange(BitConverter.GetBytes(SerialNum));

            //结果
            bytes.Add((byte)Result);

            //鉴权码
            if (Result == EnumDevRegisterType.成功 && !string.IsNullOrEmpty(AuthenticationCode))
            {
                bytes.AddRange(ParseHelper.GbkBytes(AuthenticationCode));
            }

            return bytes;
        }
    }

    /// <summary>
    /// 终端注册结果
    /// </summary>
    [JsonConverter(typeof(JsonStringEnumConverter))]
    public enum EnumDevRegisterType
    {
        成功 = 0,
        车辆已被注册 = 1,
        数据库中无该车辆 = 2,
        终端已被注册 = 3,
        数据库中无该终端 = 4
    }
}